package cn.tedu.luban.account.main.service;

import cn.tedu.luban.account.main.converter.AccountConverter;
import cn.tedu.luban.account.main.repository.AccountRepository;
import cn.tedu.luban.account.protocol.bo.AccountBO;
import cn.tedu.luban.account.protocol.dto.AccountDTO;
import cn.tedu.luban.account.protocol.param.AccountCreateParam;
import cn.tedu.luban.account.protocol.param.AccountPayParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountService {

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private AccountConverter accountConverter;

    public Long createAccount(AccountCreateParam accountCreateParam) {
        Long userId = accountCreateParam.getUserId();
        // 幂等 之前先删除再创建? 原账户有余额
        // 幂等：先查后增
        AccountBO accountBO = accountRepository.getAccountByUserId(userId);
        Long result = 0L;
        if(accountBO.getId() == null){ //判断是否存在
            // 不存在，创建新账户
            result = accountRepository.save(accountCreateParam);
        }

        return result;
    }

    public AccountDTO getAccount(Long userId) {
        AccountBO accountBO = accountRepository.getAccountByUserId(userId);
        return accountConverter.bo2dto(accountBO);
    }

    public Long mockPay(AccountPayParam param) {
        return accountRepository.updateTotalAmount(param);
    }
}
